$.Huitab("#tab_topnav .tabBar span", "#tab_topnav .tabCon", "current", "click", "0")
$(".category-tab").load("categoryTab.html");
$(".product-tab").load("productTab.html");


//保存
var isIng = false;
function preservationLists() {
    if(isIng){
        layer.msg('请求已提交，请勿重复点击！');
        return false;
    }
    isIng = true;

    if ($("input[name=applCate]:checked").val() == undefined) {
        layer.msg("如需定制商品池，规则不能为空", {icon: 5, time: 1000});
        isIng = false;
        return;
    }
    makeMap();

    var sedCateId = [];
    var sedelse = [];
    var thirId = [];
    var oneId = [];

    for (i in map1) {
        oneId.push(i);
        for (s in map1[i]) {
            if (map1[i][s].length == 0) {
                sedCateId.push(s);
            } else {
                sedelse.push(s);
                $.each(map1[i][s], function (i, item) {
                    thirId.push(item);
                })
            }
        }
    }
    //选中的二级
    var secondCategoryIdsall=""
    if(sedelse!=""){
        for (var f=0;f<sedelse.length;f++) {
            secondCategoryIdsall+=sedelse[f]+','
        }
    }
    for (var d=0;d<sedCateId.length;d++) {
        secondCategoryIdsall+=sedCateId[d]+','

    }
    //去掉最后一个逗号(如果不需要去掉，就不用写)
    if (secondCategoryIdsall.length > 0) {
        secondCategoryIdsall = secondCategoryIdsall.substr(0, secondCategoryIdsall.length - 1);
    }

    thirIds = thirId.join(',')
    oneIds = oneId.join(',')

    //三级不勾选的数据
    var filterThirdCategoryIdsall=""
    for (var e=0;e<third.length;e++) {
        filterThirdCategoryIdsall+=third[e]+','
    }
    //去掉最后一个逗号(如果不需要去掉，就不用写)
    if (filterThirdCategoryIdsall.length > 0) {
        filterThirdCategoryIdsall = filterThirdCategoryIdsall.substr(0, filterThirdCategoryIdsall.length - 1);
    }


    if (oneIds.length == 0 && doc == 0) {
        layer.msg("如需定制商品池，规则不能为空", {icon: 5, time: 1000});
        isIng = false;
        return;
    }
    var brandIds = []

    $("#append a[id]").each(function () {
        brandIds.push($(this).attr("id"))
    })
    if ($("input[name=brand]:checked").val() != 10
        && brandIds.length == 0) {
        layer.msg("如需定制商品池，规则不能为空", {icon: 5, time: 1000});
        isIng = false;
        return;
    }
    var noSend = 0
    $.each(brandIds, function (i, first) {
        $.each(brandIds, function (s, sed) {
            if (i == s) {
                return true;
            }
            if (first == sed) {
                layer.msg("品牌相同,请重试", {icon: 5, time: 1000});
                isIng = false;
                noSend = 1;
            }
        })
    })
    //保存提示
    if (noSend == 1) {
        return;
    }
    var brandIdsall=""
    if($("input[name=brand]:checked").val()==10){
        brandIdsall=""
    }else {
        brandIdsall=brandIds.join(',')
    }
    if(oneIds=="" || secondCategoryIdsall==""){
        layer.msg("如需定制商品池，规则不能为空", {icon: 5, time: 1000});
        isIng = false;
        return;
    }
    $.ajax({
        contentType: 'application/json',
        url: root.member.saveProductPoolRule,
        cache: false,  //禁用缓存
        type: "POST",
        data: JSON.stringify({
            "mainCustomerId": mainCustomerIds,
            "operateUserId": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            "operateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            "categoryFilterType": $("input[name=applCate]:checked").val(),
            "firstCategoryIds": oneIds,
            "secondCategoryIds": secondCategoryIdsall,
            "filterThirdCategoryIds": filterThirdCategoryIdsall,
            "brandIds": brandIdsall,
            "brandFilterType": $("input[name=brand]:checked").val(),

        }),

        success: function (data) {
            if (data.errorCode == 0) {
                $.Huimodalalert('定制商品池，规则设置成功！初始化正常商品池需要一定时间，请耐心等待！', 3000);
                setTimeout(function () {
                    location.replace(location.href)
                    isIng = false;
                }, 700);

            } else {
                layer.msg(data.msg, {icon: 5, time: 1000});
                isIng = false;
            }

        },
        error: function () {
            layer.msg("保存失败,请重新提交！", {icon: 5, time: 1000});
            isIng = false;
        }
    });
}
//禁用
var isIng2 = false;
function disable() {
    if(isIng2){
        layer.msg('请求已提交，请勿重复点击！');
        return false;
    }
    isIng2 = true;
    var cu = layer.confirm('<span>您即将禁用该客户组的定制商品池规则，请确认</span>', {title:'提示',btn: ['确认', '取消']}, function(index){
        $.ajax({
            url: root.member.cancelProductPoolRule,
            cache: false,
            dataType: "json",
            type: "POST",
            data:{
                mainCustomerId:mainCustomerIds
            },
            success: function (data) {
                if (data.errorCode == 0) {
                    layer.msg("规则禁用成功！", {icon: 6, time: 1000});
                    setTimeout(function () {
                        location.replace(location.href)
                        isIng2 = true;
                    }, 700);

                } else {
                    $.Huimodalalert(data.msg, 3000);
                    isIng2 = false;
                }
            }
        })
        layer.close(cu);
    },function(){
        layer.close(cu);
        isIng2 = false;

    });

}

var mainCustomerIds=sessionStorage.getItem("mainCustomerId")



/*-------------------------------------------------------------------------------------------------------------------------------------------分割线*/

//正常商品列表
getSpecialTypeId();
function getSpecialTypeId() {
    $.ajax({
        url: root.goodsInter.goods_getSpecialSkuTypes,
        cache: false, //禁用缓存
        type: "POST",
        success: function (data) {
            if (data.errorCode == 0) {
                var specialSkuTypesHtml = '<option value="" selected>不限</option><option value="-1">正常商品</option>';
                for (var i = 0; i < data.data.length; i++) {
                    specialSkuTypesHtml += '<option value="' + data.data[i].id + '">' + data.data[i].name + '</option>';
                }
                $(".specialTypeId").html(specialSkuTypesHtml);
            }
        }
    });
}

var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];

function goodsList(data) {
    console.log(data)
    if(dataSource.length>0){
        dataSource.splice(0, dataSource.length); //清空数组
    }
    if(data.data.data!=null){
        $.each(data.data.data, function(i, field) {
            var rowData = new Array();
            rowData.push(field.spu_code);
            rowData.push(field.img_url == null ? "" : field.img_url);
            rowData.push(field.name);
            rowData.push(field.subtitile == null ? "" : field.subtitile)
            rowData.push(field.brand_name);
            rowData.push(field.skuPutOnNumber);
            rowData.push(field.sale_area);
            rowData.push(field.spu_id);

            var date = new Date(field.creation_date);
            Y = date.getFullYear() + '-';
            M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
            D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
            h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
            m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()): date.getMinutes())+ ':';
            s = date.getSeconds()< 10 ? '0'+(date.getSeconds()) : date.getSeconds();

            rowData.push(Y+M+D+h+m+s);
            rowData.push(field.spu_id);
            rowData.push(field.saleAreaId);


            dataSource.push(rowData);
        });
    }

    initDataTable(dataSource);
    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "autoWidth": false,
            "ordering": true,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [50, 25, 10, 5],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [{
                "visible": true,
                "targets": 0
            },
                {
                    "render": function(data, type, row, meta) {
                        var val = '<span><td>' + row[0] + '</td></span>';
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        if(row[8] != '') {
                            var val = '<span>' + row[8] + '</span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 7
                },

                {
                    "render": function(data, type, row, meta) {
                        if(row[1] != '') {
                            var val = '<span id="spuImg1" ><img onclick="picShow(\'查看图片\',\'picShow.html\',\''+row[1]+'\')" src="'+row[1]+'" width="80" height="40"></span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 1
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = '<span class="shun_text2" style="cursor:pointer;"  title="'+ row[3] +'">'+ row[3] +'</span>';
                        return val;
                    },
                    "targets": 3
                },

            ],
            "fnInitComplete": function(oSettings, json) {
                setBtnDis(0, $("#productManage"));
                $("#datatable").on("change", '.spuId', function() {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productManage"));
                });
            }
        });
        //权限控制函数
        power()
    };
}

function goods_listCategory(categoryLevel) {
    var categoryName = $("#class1").val();
    var user_data = {
        categoryLevel: categoryLevel,
        categoryName: $("#class1").val(),
    }
    var succCallBack = function(data, status, response) {
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>"
                $("#classUl1").html(classStr);
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
                $("#classUl1").html(classStr);
            }
        }
    }
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

//获取光标
$("#class1").click(function() {
    $("#classUl1").show();
    goods_listCategory(1);
});
$(document).bind("click", function(e) {
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#classUl1").length == 0 && $(e.target).closest("#class1").length == 0) {
        //点击id为menu之外且id不是不是open，则触发
        $("#classUl1").hide()
        $("#class2").val();

    }
});
var goodslist_cantegory_id; //定义分类搜索条件

var firstCategoryId;
var secondCategoryId;
var thirdCategoryId;

// 2,3,4级的模糊查询
function getNext_input(level, category_id) {
    if(level == 4) {
        goodslist_cantegory_id = category_id;
        thirdCategoryId = category_id;
    }
    if(level < 4) {
        console.log(level)
        $("#class" + level + "")[0].oninput = function() {
            var user_data = {
                parentCateId: category_id,
                categoryName: $("#class" + level + "").val()
            }
            var succCallBack = function(data, status, response) {
                if(data.errorCode == 0) {
                    if(data.data == null) {
                        classStr = "<li>无数据</li>";
                    } else {
                        var classStr = "";
                        for(var i = 0; i < data.data.length; i++) {
                            classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                        }
                    }
                    if(data.data[0] == undefined) {
                        classValue = category_id;
                        var nextLevel = level + 1;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").hide();
                    } else {
                        var nextLevel = data.data[0].category_level;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").show();
                    }
                }
            }
            web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
        }
        //获取光标
        $("#class" + level + "").focus(function() {
            $("#classUl" + level + "").show();
        });
        $(document).bind("click", function(e) {
            //id为menu的是菜单，id为open的是打开菜单的按钮
            if($(e.target).closest("#classUl" + level + "").length == 0 && $(e.target).closest("#class" + level + "").length == 0) {
                //点击id为menu之外且id不是不是open，则触发
                $("#classUl" + level + "").hide()
            }
        });
    }

}

function nextClass(category_id, level, category_name) {
    $("#class" + level + "").val(category_name);
    if(level == 1) {
        firstCategoryId = category_id;
        $("#class2").val("");
        $("#class3").val("");
    } else if(level == 2) {
        secondCategoryId = category_id;
        $("#class3").val("");
    }
    var user_data = {
        parentCateId: category_id,
    }
    var succCallBack = function(data, status, response) {
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>";
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
            }
            if(data.data[0] == undefined) {
                classValue = category_id;
                var nextLevel = level + 1;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + level + "").hide();
            } else {
                var nextLevel = data.data[0].category_level;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + nextLevel + "").show();
                $("#classUl" + level + "").hide()
            }
        }
    }
    getNext_input(level + 1, category_id);
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}


function reloadSpuTable() {
    var customerType = $("input:checkbox[name='customerType']:checked").map(function(index,elem) {
        return $(elem).val();
    }).get().join(',');

    if(customerType.indexOf("1")>-1 && customerType.indexOf("2")>-1){
        customerType = 3;
    }
    var saleMsg = $("input:checkbox[name='saleArea']:checked").map(function(index,elem) {
        return $(elem).val();
    }).get().join(',');
    if(saleMsg == "" || saleMsg == undefined || saleMsg == null ){
        saleMsg = -1;
    }

    var categoryName = $("#class3").val();
    var firstCategoryName = $("#class1").val();
    var secondCategoryName = $("#class2").val();
    if(categoryName == "" || categoryName == undefined || categoryName == null){
        goodslist_cantegory_id = null;
        thirdCategoryId= null;
    }

    if(firstCategoryName == "" || firstCategoryName == undefined || firstCategoryName == null){
        firstCategoryId = null;
    }

    if(secondCategoryName == "" || secondCategoryName == undefined || secondCategoryName == null){
        secondCategoryId = null;
    }

    $.ajax({
        contentType: 'application/json',
        url: root.member.productPoollistPage,
        cache: false, //禁用缓存
        type: "POST",
        data: JSON.stringify({
            "mainCustomerId":mainCustomerIds,
            firstCategoryId : firstCategoryId,
            secondCategoryId :secondCategoryId,
            thirdCategoryId: goodslist_cantegory_id,
            spuCode: $("#spu_code").val(),
            spuName:$("#goodsName").val(),
            skuCode:$("#Code").val(),
            aliasName:$("#aliasParam").val(),
            restricted:$("#isLimitCategory ").val(),
            helpcode:$("#helpcode").val(),
            standards:$("#spuStandards ").val(),
            customerType:customerType,
            brandName:$("#brandName").val(),
            creationDateBegin:$("#creationDateBegin").val(),
            creationDateEnd:$("#creationDateEnd").val(),
            saleArea:saleMsg,
            specialTypeId:$(".specialTypeId").val(),
            proUseable:$("#proUseable").val(),
            pageSize: 50,
            pageNum: 1,
        }),
        success: function(data) {
            goodsList(data);
            $("#spu_all").attr("checked", false);
            var totalPages=0
            console.log(data.data)
            if (data.data.data!="") {
                totalPages=data.data.pageCount
            }else {
                totalPages=0
            }
            $('.M-box3').pagination({
                pageCount: totalPages,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function(api) {
                    console.log(api.getCurrent());
                    $.ajax({
                        contentType: 'application/json',
                        url: root.member.productPoollistPage,
                        cache: false, //禁用缓存
                        type: "POST",
                        data: JSON.stringify({
                            "mainCustomerId":mainCustomerIds,
                            firstCategoryId : firstCategoryId,
                            secondCategoryId :secondCategoryId,
                            thirdCategoryId: goodslist_cantegory_id,
                            spuCode: $("#spu_code").val(),
                            spuName:$("#goodsName").val(),
                            skuCode:$("#Code").val(),
                            aliasName:$("#aliasParam").val(),
                            restricted:$("#isLimitCategory ").val(),
                            helpcode:$("#helpcode").val(),
                            standards:$("#spuStandards ").val(),
                            customerType:customerType,
                            brandName:$("#brandName").val(),
                            creationDateBegin:$("#creationDateBegin").val(),
                            creationDateEnd:$("#creationDateEnd").val(),
                            saleArea:saleMsg,
                            specialTypeId:$(".specialTypeId").val(),
                            proUseable:$("#proUseable").val(),
                            pageSize: 50,
                            pageNum: api.getCurrent(),
                        }),
                        success: function(data) {
                            goodsList(data);
                            $("#spu_all").attr("checked", false);
                        }
                    });
                }
            });
        }
    });
}
function picShow(title, url, imgUrl) {
    window.event ? window.event.cancelBubble = true : e.stopPropagation();
    sessionStorage.setItem("imgUrlsss", imgUrl);
    layer_show(title, url, "800", "500");
}
function setBtnDis(num, pnode) { //如果选中项为空时，置灰相关按钮
    if(num <= 0) {
        pnode.find(".goods_edit").attr("disabled", "disabled").addClass("dis_btn");
    } else {
        pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
    }
}

//全选全不选
function goodselection() {
    if($("#saleAreas").is(':checked')==true){
        var saleArea=$("input:checkbox[name='saleArea']")
        for(var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = true;
        }
    }else {
        var saleArea=$("input:checkbox[name='saleArea']")
        for(var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = false;
        }
    }

}
//子级选中
goodselectionall()
function goodselectionall() {
    var saleArea=$("input:checkbox[name='saleArea']")
    var saleArea2=$("input:checkbox[name='saleArea']:checked")
    if(saleArea2.length==saleArea.length){
        $("#saleAreas").prop("checked", true)
    }else {
        $("#saleAreas").prop("checked", false)
    }
}